// pages/myself/myself.js
let network = null;
let utils = null;
let api = null;
let storage = null;
let Zan = require('../../dist/index');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
const app = getApp();

Page(Object.assign({}, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    avatarUrl: null,
    nickName: null,
    mobile: null,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseMobile: wx.canIUse('button.open-type.getPhoneNumber'),
    Expired: false,
    memberendtime: '',
    coupon:''

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    storage = new app.Storage();
    // 注册列表刷新事件
    WxNotificationCenter.addNotification("GetStoreInfo", this.refreshNotification, this);
    WxNotificationCenter.addNotification("MemberRefreshNotification", this.refreshNotification, this);
    WxNotificationCenter.addNotification("MyMemberRefreshNotification", this.refreshNotification, this);
    WxNotificationCenter.addNotification("integralRefreshNotification", this.refreshNotification, this);
    WxNotificationCenter.addNotification("couponRefreshNotification", this.refreshNotification, this);
    // saveUserInfo(this);
    this.onPullDownRefresh();
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
      if (app.globalData.userInfo.avatarUrl) {
        this.setData({
          avatarUrl: app.globalData.userInfo.avatarUrl
        })
      }
    } else {
      app.userInfoCallback = res => {
        this.setData({
          userInfo: app.globalData.userInfo,
          avatarUrl: res.avatarUrl
        })
      }
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    WxNotificationCenter.removeNotification("GetStoreInfo", this);
    WxNotificationCenter.removeNotification("MemberRefreshNotification", this);
    WxNotificationCenter.removeNotification("MyMemberRefreshNotification", this);
    WxNotificationCenter.removeNotification("integralRefreshNotification", this);
    WxNotificationCenter.removeNotification("couponRefreshNotification", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
    network._post_json(this, api.getUserInfo, {
      appId: app.globalData.appId,
      openId: app.globalData.openId
    }, getUserInfosuccess);
    this.setData({
      coupon: ''
    })
    network._post_json(this, api.getMyCoupon, { status: 0, storeId: app.globalData.store.id }, couponSuccess);

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  refreshNotification: function() {
    this.onPullDownRefresh();
  },
  /**
   * 回调门店信息
   */
  getStoreInfo: function (e) {
    this.onPullDownRefresh();
  },
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  goInfo: function(e) {
    wx.navigateTo({
      url: '/pages/myself/info/Info',
    })
  },
  /**
   * 如果用户已授权，并且用户昵称不为空，则直接弹框
   */
  getInfo: function(e) {
    console.log(e.detail.userInfo);
    if (e.detail.userInfo) {
      app.globalData.userInfo.avatarUrl = e.detail.userInfo.avatarUrl;
      app.globalData.userInfo.nickName = e.detail.userInfo.nickName;
      app.globalData.userInfo.gender = e.detail.userInfo.gender;
      this.setData({
        userInfo: app.globalData.userInfo,
        avatarUrl: e.detail.userInfo.avatarUrl,
        nickName: e.detail.userInfo.nickName,
      });
      console.log('+++++++++++++++++++++++++++++++')
      console.log(e.detail.userInfo.gender);
      network._post_json(this, api.modifyUserInfo, { nickName: this.data.nickName, avatarUrl: this.data.avatarUrl, gender: e.detail.userInfo.gender }, function () { });
    }
  },

  /**
   * 获取手机号
   */
  getPhoneNumber: function(e) {
    let that = this;
    if (e.detail.encryptedData) {
      // 校验用户当前session_key是否有效
      wx.checkSession({
        success: function() {
          network._post_json(that, api.decodePhone, {
            appId: app.globalData.appId,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            sessionKey: app.globalData.sessionKey
          }, bindSuccess);
        },
        fail: function() {
          // session_key 已经失效，重新登录
          wx.login({
            success: function(res) {
              // 获取jsCode
              let jsCode = res.code;
              wx.request({
                url: api.getOpenId,
                method: 'POST',
                data: {
                  prAppid: app.globalData.appId,
                  code: jsCode
                },
                success: function(res) {
                  console.log(res.data);
                  let sessionKey = res.data.data.session_key;
                  network._post_json(that, api.decodePhone, {
                    appId: app.globalData.appId,
                    encryptedData: e.detail.encryptedData,
                    iv: e.detail.iv,
                    sessionKey: sessionKey
                  }, bindSuccess);
                }
              })
            },
            fail: function(res) {
              console.log(res);
            }
          })

        }
      })

    }
  },

  /**
   * 会员福利
   */
  openMember: function(e) {
    wx.navigateTo({
      url: '/pages/myself/member/Member',
    })
  },

  /**
   * 我的员会
   */
  goMyMember: function(e) {
    wx.navigateTo({
      url: '/pages/myself/member/MyMember',
    })
  },

  /**
   * 余额明细
   */
  goBalance: function(e) {
    wx.navigateTo({
      url: '/pages/myself/balance/Balance'
    })
  },

  /**
   * 我的积分
   */
  gointegral: function(e) {
    wx.navigateTo({
      url: '/pages/myself/integral/Integral'
    })
  },

  /**
   * 我的订单
   */
  goOrder: function(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/myself/order/Order?index=' + id
    })
  },

  /**
   * 我的代金卷
   */
  goCoupon: function(e) {
    wx.navigateTo({
      url: '/pages/myself/coupon/Coupon',
    })
  },

  /**
   * 分享返利
   */
  goQrcode: function(e) {
    wx.navigateTo({
      url: '/pages/myself/commission/Qrcode'
    })
  },

  // goShopInfo: function (e) {
  //   if (utils.canTap(e)) {
  //     wx.navigateTo({
  //       url: '/pages/myself/store/StoreInfo'
  //     })
  //   }
  // },

  // goCustomerService: function (e) {
  //   if (utils.canTap(e)) {
  //     wx.navigateTo({
  //       url: '/pages/myself/commission/CustomerService'
  //     })
  //   }
  // },

  // goAbout: function (e) {
  //   if (utils.canTap(e)) {
  //     wx.navigateTo({
  //       url: '/pages/myself/about/About'
  //     })
  //   }
  // },

  goMySpellGroup: function(e) {
    wx.navigateTo({
      url: '/pages/myself/myspellgroup/MySpellGroup?index=0',
    })
  }

}))

//保存微信的用户资料到小程序
// var saveUserInfo = function (that) {
//   wx.getUserInfo({
//     success: res => {
//       app.globalData.avatarUrl = res.userInfo.avatarUrl;
//       app.globalData.nickName = res.userInfo.nickName;
//       that.setData({
//         userInfo: app.globalData.userInfo,
//         avatarUrl: res.userInfo.avatarUrl,
//         nickName: res.userInfo.nickName,
//       });
//     }
//   })
// }


var success = function(that, res) {
  that.setData({
    avatarUrl: app.globalData.userInfo.avatarUrl,
    nickName: app.globalData.userInfo.nickName
  });
}

var bindSuccess = function(that, res) {
  if (res.data.data) {
    app.globalData.userInfo.mobile = res.data.data.mobile;
    that.setData({
      userInfo: app.globalData.userInfo
    });
  }

}

// 注水数据
var saleInfoSuccess = function(that, res) {
  if (res.data.data) {
    that.setData({
      saleInfo: res.data.data,
    })
  }
}

// // 签到成功
// var signSuccess = function (that, res) {
//   if (res.data.data) {
//     storage.setSign();
//     that.setData({
//       isSign: '已签到'
//     })
//   }
// }
//判断会员卡到期
var getUserInfosuccess = function(that, res) {
  if (res.data.data) {
    app.globalData.userInfo = res.data.data;
    that.setData({
      userInfo: res.data.data,
      avatarUrl: res.data.data.avatarUrl,
      nickName: res.data.data.nickName,
    })
    if (res.data.data.memberendtime) {
      var NowTime = new Date().getTime();
      var total_micro = res.data.data.memberendtime * 1000 - NowTime;
      console.log("endTime" + res.data.data.memberendtime * 1000);
      console.log("NowTime" + NowTime);
      console.log("total_micro" + total_micro);
      if (total_micro <= 0) {
        that.setData({
          Expired: true,
          userInfo: res.data.data
        })
      } else {
        that.setData({
          Expired: false,
          userInfo: res.data.data
        })
      }
    }
  }

}
/**
 * 个人地信息
 */
var personMemberSuccess = function(that, res) {
  if (res.data.data) {
    that.setData({
      member: res.data.data
    })
  }
}

var fromIdSuccess = function(that, res) {}

var sendCoupnSuccess = function(that, res) {}
var couponSuccess = function(that,res){
  if (res.data.data) {
    that.setData({
      coupon:res.data.data
    })

  }
}